<template>
  <div id="root">
    <el-row>
      <el-col :span="8" class="root-left">
        <div class="grid-content">
          <el-form :model="ruleForm" status-icon
                   :rules="rules" ref="ruleForm"
                   label-width="100px"
                   class="demo-ruleForm">

            <el-form-item label="项目名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                type="text">
              </el-input>
            </el-form-item>
            <el-form-item label="开始时间" prop="start">
              <el-date-picker
                v-model="ruleForm.start"
                type="date"
                placeholder="选择开始日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="end">
              <el-date-picker
                v-model="ruleForm.end"
                type="date"
                placeholder="选择结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="项目描述" prop="desc">
              <el-input

                v-model="ruleForm.desc"
                type="textarea">
              </el-input>
            </el-form-item>

            <el-form-item label="项目文件" prop="file">
              <div class="el-upload-dragger" style="margin-left: 28px">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :file-list="fileobj"
                  :http-request="httpRequest"
                  :auto-upload="false">
                  <div style="height: 50px;" class="el-icon-upload"></div>
                  <div class="el-upload__text"> 将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </div>
            </el-form-item>

            <el-form-item>

              <el-button style="margin-left: 10px;" type="primary" @click="submitUpload('ruleForm')">提交
              </el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="14" class="root-right">
        <h3 style="margin-top: 30px;margin-left:20px;margin-bottom:20px;text-align: left;color: #8c939d">
          未完成的部门任务
        </h3>
        <div class="show-message">
          <el-table
            height="400"
            :data="tableDatas"
            style="width: 100%;"
          >

            <el-table-column
              label="项目名称"
              prop="name"
              width="120">
            </el-table-column>
             <el-table-column
              prop="desc"
              label="项目描述"
            >
            </el-table-column>
            <el-table-column
              label="开始时间"
              prop="start"
              width="100">
            </el-table-column>
            <el-table-column
              prop="end"
              label="结束时间"
              width="120"
            >
            </el-table-column>
            <el-table-column
              label="项目文件"
              prop="file"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="warning"
                  @click="downloadfile(scope.$index, scope.row)">下载
                </el-button>
              </template>
            </el-table-column>

            <el-table-column label="操作"
                             width="110"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagenation">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            :page-size="page_size"
            @prev-click="prevfun"
            @next-click="nextfun"
            @current-change="currentchange"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  export default {
    name: 'TaskPartView',
    data () {

      var name = (rule, value, callback) => {
        if (value === '' || !value) {
          return callback(new Error('项目名称不能为空'))

        }
        callback()
      }
      var start = (rule, value, callback) => {
        if (value === ''|| !value) {
          return callback(new Error('开始时间不能为空'))

        }
        callback()
      }
      var end = (rule, value, callback) => {
        if (value === ''|| !value) {
          return callback(new Error('结束时间不能为空'))

        }
        callback()
      }
       var desc = (rule, value, callback) => {
        if (value === ''|| !value) {
          return callback(new Error('项目描述不能为空'))

        }
        callback()
      }
      var file = (rule, value, callback) => {
        if (value === ''|| !value) {
          return callback(new Error('请上传项目文件！！'))

        }
        callback()
      }



      return {
        hours: '',
        download_url: '',
        fileobj: [],//显示上传的文件
        options: [],//部门
        form: {
          title: '',
          content: ''
        },
        formLabelWidth: '100px',
        visited: false, //控制对话框的弹出
        total: 5, //先设置给初始值，只给空字符串''会报typeerror
        //下一页
        next: '',
        //上一页
        prev: '',
        //每页总数
        page_size: 1,//先设置给初始值，只给空字符串''会报typeerror
        //展示的数据
        tableDatas: [],
        ruleForm: {
          file:'not'//原来判断用户是否上传文件了

        },
        rules: {
          name: [
            {
              validator: name,
              trigger: 'blur'
            }
          ],
          start:[
              {
              validator: start,
              trigger: 'blur'
            }
          ],
           end:[
              {
              validator: end,
              trigger: 'blur'
            }
          ],
          desc:[
              {
              validator: desc,
              trigger: 'blur'
            }
          ],
          file:[
              {
              validator: file,
              trigger: 'blur'
            }
          ],
        }

      }
    },
    mounted () {
      this.download_url = this.$settings.base_url + '/user/downloadfile/'
      //获取公司文件
      this.get_data()

    },
    methods: {
      //submit（）执行后自动调用这个函数
      httpRequest (params) {
        var FileExt = params.file.name.split('.')[1]
        //只能上传pdf格式的文件
        var file_type = ['pdf', 'PDF'].indexOf(FileExt) === -1
        if (file_type) {
          this.$message({
            type: 'warning',
            message: '请上传pdf格式文件'
          })
          this.fileobj = []
          return
        }


        const isLt2M = params.file.size / 1024 / 1024 < 30
        if (!isLt2M) {
          this.$message.warning('上传的文件大小不能超过30MB')
          return
        }
       if (this.ruleForm.start>this.ruleForm.end){
         this.$message.error('项目结束时间应该晚于项目开始时间！！')
         return
       }

        this.ruleForm.file = params.file
        var formdata = new FormData()
        formdata.append('file', this.ruleForm.file)
        formdata.append('name', this.ruleForm.name)
        formdata.append('desc', this.ruleForm.desc)
        formdata.append('start', this.$moment(this.ruleForm.start).format('YYYY-MM-DD'))
        formdata.append('end', this.$moment(this.ruleForm.end).format('YYYY-MM-DD'))
        formdata.append('manage','')
        this.$axios({
          url: this.$settings.base_url + '/user/task/',
          method: 'post',
          data: formdata
        }).then(res => {
          if (res.data.code === 100) {
            this.$message.success('项目发布成功')
            this.get_data()
            this.resetForm('ruleForm')
            this.fileobj = []
          } else {
            this.$message.error(res.data.error)
            this.fileobj = []
          }
        })
      },
      //点击提交时调用这个
      submitUpload (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //前端上传文件到浏览器
            this.$refs.upload.submit()//执行完会走httpRequest函数
          } else {
            console.log('error submit!!')
          }
        })
      },
      downloadfile (index, row) {
        var arr = row.file.split('.')// /medai/companyfile/新员工手册.docx
        var file_type = arr[arr.length - 1]//获取文件的格式
        this.$confirm('确认下载该项目文件吗？').then(res => {
          this.$axios({
            method: 'get', // 如果是get方法，则写“GET”
            url: this.$settings.base_url + `/user/downtask/?id=${row.id}`,
            responseType: 'blob'
          })
            .then(res => {

              let blob = new Blob([res.data], {
                type: 'application/msword' //这里需要根据不同的文件格式写不同的参数
              })

              let eLink = document.createElement('a')
              eLink.download = `${row.name}.${file_type}` //给文件名和指定格式,浏览器下载时看到的
              eLink.style.display = 'none'
              eLink.href = URL.createObjectURL(blob)
              document.body.appendChild(eLink)
              eLink.click()
              URL.revokeObjectURL(eLink.href)
              document.body.removeChild(eLink)
            })
            .catch(err => {
            })
        }).catch(error => {
          this.$message.warning('取消下载')
        })

      },

      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.fileobj = []
      },
      get_data (page = 1) {
        this.$axios({
          url: this.$settings.base_url + `/user/task/?page=${page}`,
          method: 'get'
        }).then(res => {
          //获取到用户信息，赋值给变量
          this.tableDatas = res.data.results
          // this.prev = res.data.links.previous
          // this.next = res.data.links.next
          this.total = res.data.count
          this.page_size = res.data.page_size
        })
      },
      prevfun (value) {
        //value拿到的当前的页码,不用传递，内置的函数，自动传递要前往的页码
        this.get_data(value)
      },
      nextfun (value) {
        //value拿到页码
        this.get_data(value)
      },
      currentchange (value) {
        this.get_data(value)

      },

      handleDelete (index, row) {
        console.log(row)
        this.$confirm('此操作将永久删除此项目任务， 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({
            url: this.$settings.base_url + `/user/task/?id=${row.id}`,
            method: 'delete',
          }).then(res => {
            if (res.data.code === 100) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.get_data()
            } else {
              this.$message.error('无此数据，无法删除')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .root-left {
    margin-top: 30px;
    margin-right: 50px;
  }

  .el-upload-dragger {
    width: 240px;
    text-align: center;
  }
</style>
